package com.example.demo111111.controller;
import com.example.demo111111.common.EasyExcelUtil;
import com.example.demo111111.entity.Book;
import com.example.demo111111.service.BookService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

/**
 * 文件导入导出控制层
 * @author CWW
 * @date 2024/12/18 11:42
 */
@Validated
@RestController
@RequestMapping("/book")
public class BookController {

    @Resource
    private BookService bookService;

    /**
     * 文件导入
     *
     * @param file excel文件
     * @return 执行结果
     */
    @PostMapping("/upload")
    public Boolean readFile1(MultipartFile file) throws Exception {
        // 定义一个接收表格内容的集合
        List<Book> list;
        // 读取文件内容
        try {
            //获取excel文件的字节流，封装成book对象
            list = EasyExcelUtil.readMultipartFile(file.getInputStream(), Book.class);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

        //将book数据逐个插入到数据库中
        for (Book book : list) {
            //将book插入到数据库
            bookService.addBook(book);
        }


        return true;
    }

    /**
     * 导出excel文件
     *
     * @param response 响应体
     */
    @PostMapping("/download")
    public void downFile1(HttpServletResponse response) {
        // 获取用户信息列表
        List<Book> allBook = bookService.findAllBook();


        // 导出文件
        EasyExcelUtil.export(response, "书籍列表", "书籍清单", allBook,Book.class);
    }

}
